<template>
  <div>
    <!-- TopCard -->
    <el-card style="height: 80px">
      <el-form class="form">
        <el-form-item label="用户名:">
          <el-input v-model="searchKey"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @Click="searchClick" type="primary">搜索</el-button>
          <el-button @click="reset" type="primary">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- TableCard -->
    <el-card class="below_content">
      <el-button type="primary" @click="addUser">添加用户</el-button>
      <el-button type="primary" @click="deleteBatchOfUser">批量删除</el-button>
      <el-table
        v-model:data="userArr"
        @selection-change="handleSelectionChange"
        style="margin: 15px 0"
      >
        <el-table-column type="selection" />
        <el-table-column label="#" type="index" />
        <el-table-column label="ID" width="80" prop="id" />
        <el-table-column label="用户名字" prop="username" />
        <el-table-column label="昵称" prop="name" />
        <el-table-column label="用户角色" prop="roleName" />
        <el-table-column label="创建时间" prop="createTime" />
        <el-table-column label="更新时间" prop="updateTime" />
        <el-table-column label="操作">
          <template #default="{ row, $index }">
            <el-button @click="setRole(row)" type="success" icon="user">
              管理用户
            </el-button>
            <el-button
              @click="updateUser(row)"
              type="primary"
              icon="edit"
            ></el-button>
            <el-button
              @click="removeUser(row)"
              type="danger"
              icon="delete"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[2, 5, 7, 9]"
        layout=" prev, pager, next, jumper,->,sizes,total"
        :total="total"
        @change="handleChange"
      />
    </el-card>
    <!-- 添加/修改用户抽屉 -->
    <el-drawer
      v-model="drawer"
      :title="userParams.id ? '修改用户' : '添加用户'"
    >
      <el-form ref="formRef" :model="userParams" :rules="rules">
        <el-form-item prop="username" label="用户姓名">
          <el-input v-model="userParams.username" type="text"></el-input>
        </el-form-item>
        <el-form-item prop="name" label="用户昵称">
          <el-input v-model="userParams.name" type="text"></el-input>
        </el-form-item>
        <el-form-item prop="password" v-if="!userParams.id" label="用户密码">
          <el-input v-model="userParams.password" type="text"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancelClick">取消</el-button>
        <el-button type="primary" @click="confirmClick">确定</el-button>
      </template>
    </el-drawer>
    <!-- 分配角色抽屉 -->
    <el-drawer v-model="drawer1" title="分配用户角色">
      <el-form>
        <el-form-item label="用户名称: ">
          {{ userParams.username }}
        </el-form-item>
      </el-form>
      <el-checkbox
        v-model="checkAll"
        :indeterminate="isIndeterminate"
        @change="handleCheckAllChange"
      >
        全选
      </el-checkbox>
      <el-checkbox-group
        v-model="userRole"
        @change="handleCheckedUserRoleChange"
      >
        <el-checkbox v-for="r in allRole" :key="r.id" :label="r" :value="r">
          {{ r.roleName }}
        </el-checkbox>
      </el-checkbox-group>
      <template #footer>
        <el-button @click="cancelAssign">取消</el-button>
        <el-button @click="confirmAssign" type="primary">确定</el-button>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, nextTick, reactive } from 'vue'
import {
  reqUserInfo,
  reqAddOrUpdateUser,
  reqAllRole,
  reqAssignRole,
  reqDeleteUsers,
  reqDeleteSelectedUser,
} from '../../../api/acl/user'
import {
  SetRoleData,
  UserResponseData,
  Records,
  User,
  AllRoleResponseData,
  AllRole,
} from '../../../api/acl/user/type.ts'
import { ElMessage } from 'element-plus'

let currentPage = ref<number>(1)
let pageSize = ref<number>(2)
let total = ref<number>()
let userArr = ref<Records>([])
let drawer = ref(false) //控制抽屉的显示与隐藏
let userParams = reactive<User>({
  username: '',
  name: '',
  password: '',
})
let formRef = ref()
const searchKey = ref<string>('')
const drawer1 = ref<boolean>(false)
const checkAll = ref<boolean>(false)
const isIndeterminate = ref<boolean>(true)
const allRole = ref<AllRole>([])
const userRole = ref<AllRole>([])

// #region 表单校验
// 自定义表单校验username和name
const validateUserNameOrName = (rule: any, value: any, callBack: any) => {
  const usernameRegex = /^(?!\d+$)(?![a-zA-Z]+$).+$/
  if (!usernameRegex.test(value) && value !== '') {
    callBack(new Error('不能仅由字母或数字组成'))
  } else if (value == 'admin') {
    callBack(new Error('用户名已存在'))
  } else {
    callBack()
  }
}
// 表单自定义校验password
const validateUserPassword = (rule: any, value: any, callBack: any) => {
  const passwordRegex = /^(?=.*[a-zA-Z])(?=.*\d).+$/
  if (!passwordRegex.test(value)) {
    return callBack(new Error('密码至少包含字母和数字'))
  } else {
    callBack()
  }
}

// 表单校验规则属性
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 13, message: '用户长度请控制在2-13位', trigger: 'blur' },
    { trigger: 'blur', validator: validateUserNameOrName },
  ],
  name: [
    { required: true, message: '请输入用户昵称', trigger: 'blur' },
    { min: 2, max: 13, message: '用户长度请控制在2-13位', trigger: 'blur' },
    { trigger: 'blur', validator: validateUserNameOrName },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 13, message: '用户长度请控制在6-13位', trigger: 'blur' },
    { trigger: 'blur', validator: validateUserPassword },
  ],
}
// #endregion _表单校验

/* 分页器change事件 */
let handleChange = () => {
  getHasUser()
}
/* 获取已有用户信息 */
const getHasUser = async () => {
  let res: UserResponseData = await reqUserInfo(
    currentPage.value,
    pageSize.value,
    searchKey.value,
  )
  if (res.code == 200) {
    total.value = res.data.total
    userArr.value = res.data.records
  }
}
/* 添加用户按钮 */
const addUser = async () => {
  // 每次进来清空上次收集表单数据
  Object.assign(userParams, {
    id: '',
    username: '',
    name: '',
    password: '',
  })
  // 清理之前的校验信息
  nextTick(() => {
    formRef.value.clearValidate('username')
    formRef.value.clearValidate('name')
    formRef.value.clearValidate('password')
  })

  drawer.value = true
}
/* 点击编辑按钮 */
const updateUser = (row: User) => {
  nextTick(() => {
    formRef.value.clearValidate('username')
    formRef.value.clearValidate('name')
  }) // 清理之前的校验信息
  drawer.value = true
  Object.assign(userParams, row) // 每次进来绑定当前用户对象row的表单数据
}

/* 修改/新增用户抽屉的取消按钮 */
const cancelClick = () => {
  drawer.value = false
}
/* 添加/修改抽屉的确定按钮 */
const confirmClick = async () => {
  console.log('userParams.password:' + userParams.password)
  try {
    await formRef.value.validate()
    drawer.value = false
    let res: any = await reqAddOrUpdateUser(userParams)
    if (res.code == 200) {
      ElMessage({
        type: 'success',
        message: userParams.id ? '修改成功' : '添加成功',
      })
      drawer.value = false
      getHasUser()
    } else {
      drawer.value = false
      ElMessage({
        type: 'error',
        message: userParams.id ? '修改失败' : '添加失败',
      })
    }
  } catch (error) {
    ElMessage({
      type: 'error',
      message: '表单校验不通过',
    })
  }
}

// #region _分配角色抽屉相关

/* 管理用户按钮 */
const setRole = async (row: User) => {
  drawer1.value = true
  console.log(row)

  Object.assign(userParams, row)
  let res: AllRoleResponseData = await reqAllRole(userParams.id as number)
  allRole.value = res.data.allRolesList
  userRole.value = res.data.assignRoles
}

/* 当checkAll发送变化时 */
const handleCheckAllChange = (val: boolean) => {
  userRole.value = val ? allRole.value : []
  isIndeterminate.value = false
}

/* change:当el-checkbox-group绑定值变化时触发的事件 */
const handleCheckedUserRoleChange = (value: string[]) => {
  checkAll.value = value.length === userRole.value.length
  isIndeterminate.value = value.length !== allRole.value.length
}

/*  分配角色取消按钮 */
const cancelAssign = () => {
  drawer1.value = false
}

/*  分配角色确定按钮 */
const confirmAssign = async () => {
  // let roleIdList = (userRole.value).map(item=>item.id)
  // // 这个入参的key: 一定要与接口一致
  // let params = {roleIdList,userId:userParams.id}
  // console.log(params);

  //收集参数_老师的优雅代码
  let data: SetRoleData = {
    userId: userParams.id as number,
    roleIdList: userRole.value.map((item) => item.id as number),
  }
  try {
    await reqAssignRole(data)
    ElMessage({
      type: 'success',
      message: '分配角色成功',
    })
  } catch (error) {
    ElMessage({
      type: 'error',
      message: '分配角色失败',
    })
  }
  drawer1.value = false
  getHasUser()
}
// #endregion _分配角色抽屉相关

// #region _删除业务相关
const batchOfDeleteUsersArr = ref(null)

/* 根据id删除func */
const removeUser = async (row: User) => {
  console.log(row.id)
  let id = row.id as number
  try {
    await reqDeleteUsers(id)
    ElMessage({
      type: 'success',
      message: '删除用户成功',
    })
    getHasUser()
  } catch (error) {
    ElMessage({
      type: 'error',
      message: '删除用户失败',
    })
  }
}

/* table的selection-change事件: 收集batchOfDeleteUsersArr删除数组 */
const handleSelectionChange = (val: AllRole) => {
  console.log('handleSelectionChange')
  batchOfDeleteUsersArr.value = val.map((item) => item.id)
}

/* 批量删除用户func */
const deleteBatchOfUser = async () => {
  let res = await reqDeleteSelectedUser(batchOfDeleteUsersArr.value)
  if (res.code == 200) {
    ElMessage({
      type: 'success',
      message: '批量删除用户成功',
    })
    getHasUser()
  } else {
    ElMessage({
      type: 'error',
      message: '删除用户失败',
    })
  }
}

// #endregion _删除业务相关

/* 点击搜索按钮 */
const searchClick = async () => {
  getHasUser()
  searchKey.value = ''
}

const reset = () => {}

onMounted(() => {
  getHasUser()
})
</script>
<style scoped>
.form {
  display: flex;
  flex-flow: row nowrap;
  justify-content: space-between;
}

.below_content {
  margin-top: 15px;
}
</style>
